const pool = require('../config/db');
const { v4: uuidv4 } = require('uuid');

const Message = {
    async createConversation(user_ids) {
        const conversation_id = uuidv4();
        const connection = await pool.getConnection();

        try {
            await connection.beginTransaction();

            await connection.query('INSERT INTO conversations (conversation_id) VALUES (?)', [conversation_id]);

            for (const user_id of user_ids) {
                await connection.query(
                    'INSERT INTO conversation_participants (conversation_id, user_id) VALUES (?, ?)',
                    [conversation_id, user_id]
                );
            }

            await connection.commit();
            return { conversation_id };
        } catch (error) {
            await connection.rollback();
            throw error;
        } finally {
            connection.release();
        }
    },

    async create({ conversation_id, user_id, content }) {
        const message_id = uuidv4();
        await pool.query(
            'INSERT INTO messages (message_id, conversation_id, user_id, content) VALUES (?, ?, ?, ?)',
            [message_id, conversation_id, user_id, content]
        );
        return { message_id };
    },

    async findByConversationId(conversation_id, limit = 20, offset = 0) {
        const [rows] = await pool.query(
            'SELECT m.*, u.username FROM messages m JOIN users u ON m.user_id = u.user_id WHERE m.conversation_id = ? ORDER BY m.created_at DESC LIMIT ? OFFSET ?',
            [conversation_id, limit, offset]
        );
        return rows;
    }
};

module.exports = Message;